package com.cicadasmall.system.service.impl;

import com.cicadasmall.common.base.BaseService;
import com.cicadasmall.common.exception.ServiceException;
import com.cicadasmall.common.func.Fn;
import com.cicadasmall.common.resp.R;
import com.cicadasmall.system.dto.OauthClientDetailsInputDTO;
import com.cicadasmall.system.dto.OauthClientDetailsQueryDTO;
import com.cicadasmall.system.dto.OauthClientDetailsUpdateDTO;
import com.cicadasmall.data.domain.OauthClientDetailsDO;
import com.cicadasmall.data.mapper.SysOauthClientDetailsMapper;
import com.cicadasmall.system.service.IOauthClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author westboy
 * @date 2019-06-19
 */
@Service
public class OauthClientDetailsServiceImpl extends BaseService<SysOauthClientDetailsMapper, OauthClientDetailsDO> implements IOauthClientDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public R page(OauthClientDetailsQueryDTO oauthClientDetailsQueryDTO) {
        OauthClientDetailsDO oauthClientDetails = oauthClientDetailsQueryDTO.convertToEntity();
        return R.ok(baseMapper.selectPage(oauthClientDetailsQueryDTO.page(), getLambdaQueryWrapper().setEntity(oauthClientDetails)));
    }

    @Override
    public R save(OauthClientDetailsInputDTO oauthClientDetailsInputDTO) {
        OauthClientDetailsDO oauthClientDetails = oauthClientDetailsInputDTO.convertToEntity();
        if (Fn.isEmpty(oauthClientDetails.getClientSecretStr())) {
            throw new ServiceException("ClientSecret不能为空!");
        }
        oauthClientDetails.setClientSecret(passwordEncoder.encode(oauthClientDetails.getClientSecretStr()));
        save(oauthClientDetails);
        return R.ok(true);
    }

    @Override
    public R update(OauthClientDetailsUpdateDTO oauthClientDetailsUpdateDTO) {
        OauthClientDetailsDO oauthClientDetails = oauthClientDetailsUpdateDTO.convertToEntity();
        if (Fn.isNull(oauthClientDetails.getId())) {
            throw new ServiceException("更新失败，没有主键参数！!");
        }
        if (Fn.isNotEmpty(oauthClientDetails.getClientSecretStr())) {
            oauthClientDetails.setClientSecret(passwordEncoder.encode(oauthClientDetails.getClientSecretStr()));
        }
        updateById(oauthClientDetails);
        return R.ok(true);
    }

    @Override
    public R findById(Serializable id) {
        OauthClientDetailsDO oauthClientDetails = baseMapper.selectById(id);
        return R.ok(oauthClientDetails);
    }

    @Override
    public R deleteById(Serializable id) {
        baseMapper.deleteById(id);
        return R.ok(true);
    }
}
